﻿/* Copyright 2010 Imaginary Development. All rights reserved*/
function AddDefense(line) {
    var defenseReg = new RegExp('\*\s*([a-z\s]+[a-z]):\s*([0-9,]+)', 'i');
    var defense = defenseReg.exec(line);
    if (defense == null || defense.length!=3)
        return;
    var defenseType = defense[1];
    var count =parseInt( defense[2].replace(/,/gi, ''));
    $('td.defenderBefore input').val(count);

}

function SanitizeEspionage(input) {
    return input.replace('Anti-Ballistic Missile', 'ABM').replace(/ /g, '');
}
function EspionageTypeSearch(type) {
    return type + '\s*.*\s*:';
}
function EspionageTypeCount(input, index) {
    return parseInt(input.substr(index).match('[0-9,]+')[0].replace(',', ''), 10);
}
function AppendHtml(status, input) {
    status.html(status.html() + input);
}
function ParseEspionage() {
//    var esp = $('.Espionage');
    //    esp.toggle();
    var status=$('div#status');
    status.html('');
    $('.b4').show();
    var espB4 = SanitizeEspionage($('textarea#EspionageBefore').val());
    var espAfter = SanitizeEspionage($('textarea#EspionageAfter').val());
    
    var found = false;
    $('td.b4.defenderBefore input:text').each(function(index, item) {
        var type = item.id.substring(0, item.id.length - 'DB'.length);
        var typeIndex = espB4.search(EspionageTypeSearch(type));
        if (typeIndex >= 0) {
            var count = EspionageTypeCount(espB4, typeIndex);
            item.value = count;
            var afterIndex = espAfter.search(EspionageTypeSearch(type));
            if (afterIndex >= 0 && count > 0) {
                // espAfter = espAfter.substr(afterIndex);
                var countAfter = EspionageTypeCount(espAfter, afterIndex);
                var countLost = count - countAfter;
                var defenderBox = $('td.defender input:text#' + type + 'D');
                if (defenderBox == null || defenderBox.length == 0)
                    AppendHtml(status, '<br />defenderBox missing:' + type);
               // defenderBox.value = countLost;
                defenderBox.val(countLost);
                AppendHtml(status, '<br />defenderBox for ' + type + ' changed to ' + countLost);
            }
            else {
                AppendHtml(status, '<br />Espionage mismatch for ' + type);
                return;
            }
        }
        else {
            AppendHtml(status, '<br />No ' + type + ' found');
        }
    });
//    var shipsIndex = espB4.search('SHIPS:');
//    if (shipsIndex < 0)
//        return;
//        espB4= espB4.substr(shipsIndex);
//    var defensesIndex = espB4.search('DEFENSES:');
//    if (defensesIndex < 0)
//        return;
//    espB4 = espB4.substr(defensesIndex);
//    var index = 0;
    
    
}